var is_wechat =
  window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) ==
  'micromessenger'
// var mc
var pageActiveIndex = 0
var maxPageCount = 0
var canMove = true // 是否能动
var maskLoadCount = 0 // 开屏动画的图load了几多张
var percent = 0
var domIsLoaded = false
var isloaded = false
// var ismcloaded = false
var windowWidth = window.innerWidth // 视口宽度
var windowHeight = window.innerHeight // 视口高度
var page3IsLooping = false
var page3LoopValue = 0
var page4IsLooping = false
var page5IsLooping = false
// var page6IsLooping = false
// var page7IsLooping = false
var page5Swiper
var page9Swiper
var conutImg = 0 // load了多少张序列帧F
var hPageActiveIndex = 0
var maxHPageCount = 0
var canHMove = true
var swiperTimer = null

var allLoaded = false // 全部load完未

var beginTime = 0

// 图片onerror
function imgError (img) {
  return
  src = $(this).attr('src') || $(this).attr('data-src')
  $(img).attr({
    src: src + Date.now().toString()
  })
}

console.log('20210621 1026')

// load loading的图
function loadMask () {
  maskLoadCount++
  if (maskLoadCount === 3) {
    console.log('maskLoadCount: ' + maskLoadCount)
    $('#bodyMask .blank').fadeOut(2000, function () {
      $('#bodyMask .blank').remove()
    })

    setTimeout(function () {
      beginTime = Date.now() // 开始计时
      initTimer()
    }, 3000)
  }
}

function initTimer () {
  // 全部load完未
  allLoaded =
    isloaded &&
    conutImg === $('#sequence .img-618').length &&
    domIsLoaded &&
    maskLoadCount === 3

  if (percent === 99 && allLoaded) {
    $('#sequence img')
      .removeClass('display-b')
      .addClass('display-n')

    addPercent()
    $('#bodyMask').fadeOut(1000, function () {
      $('#bodyMask').remove()
    })

    setTimeout(function () {
      sequence(0)
    }, 1200)
    return
  }

  if (percent < 99) {
    addPercent()
  }

  // 超过35秒，其他都加载完但序列帧没加载完
  if (
    Date.now() - beginTime > 35000 &&
    conutImg !== $('#sequence .img-618').length &&
    isloaded &&
    domIsLoaded
  ) {
    checkSequence()
    return
  }

  if (allLoaded) {
    setTimeout(initTimer, 40)
  } else if (percent < 40) {
    setTimeout(initTimer, 300) // 12秒
  } else if (percent < 60) {
    setTimeout(initTimer, 400) // 8秒
  } else if (percent < 90) {
    setTimeout(initTimer, 500) // 15秒
  } else {
    console.log('加载中')
    setTimeout(initTimer, 1000) // 10秒
  }
}

// 加百分比
function addPercent () {
  percent = Math.floor(percent) + 1
  $('#bodyMask .percent').text(percent)
}

// 检查序列帧有没有全部加载
function checkSequence () {
  $('#sequence .img-618').each(function () {
    if ($(this).attr('data-load') !== '1') {
      $(this).attr({
        src: $(this).attr('data-src') + Date.now().toString()
      })
    }
  })

  conutImg = $('#sequence .img-618').length

  setTimeout(function () {
    initTimer()
  }, 200)
}

// 页面所有元素加载完成时
function loaded () {
  initPage3Loop()
  // initStart()
  // initSku()
  palayLiveBroadcast()
  setTimeout(function () {
    isloaded = true
    console.log('isloaded。。conutImg：' + conutImg)
  }, 1000)
  $('.page9 .swiperH-button-prev').on('touchstart', function () {
    clearInterval(swiperTimer)
    hPageMove('right')
  })
  $('.page9 .swiperH-button-next').on('touchstart', function () {
    clearInterval(swiperTimer)
    hPageMove('left')
  })
}

// 所有dom加载完成时
$(function () {
  // 适配iphone5与iphone6
  if ((750 / windowWidth) * windowHeight <= 1334) {
    $('#bodyWrapper').addClass('ip6')
  }
  initPageMove()
  initPageHMove()
  initBgcGif()
  // initArrowUp()
  page5Func()

  domIsLoaded = true
  console.log('domIsLoaded。。conutImg：' + conutImg)
})

// 初始化页面移动
function initPageMove () {
  // 设置多少页一共
  maxPageCount = $('#pageContainer > .swiper-slide').length

  // 设置长宽高
  $('.swiper-slide').css({
    width: windowWidth,
    height: windowHeight
  })

  $('.page-container')
    .off('touchstart')
    .on('touchstart', function (e) {
      e.preventDefault()

      var startX = e.targetTouches[0].pageX
      var startY = e.targetTouches[0].pageY

      $('.page-container')
        .off('touchend')
        .on('touchend', function (endEv) {
          var moveX = endEv.changedTouches[0].pageX - startX
          var moveY = endEv.changedTouches[0].pageY - startY

          if (moveY < -50 && Math.abs(moveY) > Math.abs(moveX) * 1.3) {
            // 手指上划，且Y、X轴对比小于40°
            // 如果是最后一页了，不执行
            if (pageActiveIndex < maxPageCount - 1) {
              pageMove('down')
            }
          } else if (moveY > 50 && Math.abs(moveY) > Math.abs(moveX) * 1.3) {
            // 手指下划，且Y、X轴对比小于40°
            // 不是第一页才执行
            if (pageActiveIndex > 0) {
              pageMove('up')
            }
          }
        })
    })
}

// 页面移动
function pageMove (direction) {
  if (!canMove) return
  canMove = false
  var index = direction === 'down' ? pageActiveIndex + 1 : pageActiveIndex - 1
  anime({
    targets: '#pageContainer',
    translateY: -windowHeight * index,
    easing: 'easeInOutQuad',
    duration: 800,
    complete: function () {
      pageActiveIndex = index
      canMove = true
      switch (pageActiveIndex) {
        // case 1:
        //   page2Func()
        //   break
        // case 2:
        //   if (!page3IsLooping) {
        //     page3IsLooping = true
        //     page3Func(1)
        //   }
        //   break
        case 4:
          page4Func()
          break
        case 5:
          if (!page4IsLooping) {
            page4IsLooping = true
            if ($('#page9Swiper .swiper-wrapper-h').length > 0) {
              swiperTimerFunc()
            }
          }
          break
        case 6:
          if (!page5IsLooping) {
            page5IsLooping = true
            page5Swiper.autoplay.start()
          }
          break
        case 9:
          $('.page8 .text-618').fadeIn(2000)
          break
        default:
          break
      }
      moveBgcGif()
    }
  })
}

// 初始化bgc-gif
function initBgcGif () {
  $('.bgc-gif').css({
    width: windowWidth,
    height: windowHeight
  })
}

// 移动bgc-gif
function moveBgcGif () {
  if (pageActiveIndex === 0 || (5 <= pageActiveIndex && pageActiveIndex <= 7)) {
    $('.bgc-gif').css({
      top: windowHeight * pageActiveIndex,
      opacity: 0
    })
  } else {
    $('.bgc-gif').css({
      top: windowHeight * pageActiveIndex,
      opacity: 1
    })
  }
}

// 计数序列帧
function load618Image (img) {
  $(img).attr('data-load', '1')
  conutImg++
  if (conutImg === $('#sequence .img-618').length) {
    console.log('conutImg：' + conutImg)
  }
}

// 执行序列帧
function sequence (i) {
  var img = $('#sequence img')
  var length = img.length
  if (i >= length) return

  img
    .eq(i)
    .removeClass('display-n')
    .addClass('display-b')

  if (i > 0) {
    img
      .eq(i - 1)
      .removeClass('display-b')
      .addClass('display-n')
  }

  setTimeout(function () {
    sequence(i + 1)
  }, 41)
}

// 箭头移动函数
// function initArrowUp () {
//   anime({
//     targets: '.arrow-up',
//     translateY: '-8vw',
//     easing: 'easeInOutQuad',
//     duration: 1100,
//     loop: true
//   })
// }

// 第四页运动函数
function page4Func () {
  anime({
    targets: '.page4 .logo-list',
    duration: 8000,
    scale: 1,
    delay: 200,
    opacity: 1
  })
}

// 第二页运动函数
// function page2Func () {
//   anime({
//     targets: '.page2 .title',
//     translateX: '78vw',
//     easing: 'easeInOutQuad',
//     duration: 1200,
//     delay: 200,
//     opacity: 1
//   })

//   anime({
//     targets: '.page2 .meow',
//     translateX: '-91.75vw',
//     easing: 'easeInOutQuad',
//     duration: 1200,
//     delay: 500,
//     opacity: 1
//   })

//   anime({
//     targets: '.page2 .no1',
//     translateX: '113.1vw',
//     easing: 'easeInOutQuad',
//     duration: 1200,
//     delay: 700,
//     opacity: 1
//   })
// }

// 处理第三页自动滚动轮播高度
function initPage3Loop () {
  // 设置高度
  var loopItem = $('.page3-loop .loop-item').eq(0)
  var height = loopItem.height()
  var paddingBottom = Number(loopItem.css('padding-bottom').split('px')[0])
  var setHeight = height * 3 + paddingBottom * 2
  $('.page3-loop').css({
    height: setHeight + 2
  })

  // 复制一次.loop-wrapper-1并改className
  // var newLoop = $('.loop-wrapper-1').clone()
  // newLoop.removeClass('loop-wrapper-1').addClass('loop-wrapper-2')
  // $('.loop-wrapper-1').after(newLoop)

  // loop
  page3LoopValue = height + paddingBottom
}

// 第三页运动函数
// function page3Func (i) {
//   var index = i
//   if (index === 7) {
//     $('.page3-loop .loop-wrapper').css({
//       transform: 'translateY(0)'
//     })
//     index = 1
//   }
//   anime({
//     targets: '.page3-loop .loop-wrapper',
//     translateY: -(index * page3LoopValue),
//     easing: 'easeInOutQuad',
//     delay: 750,
//     complete: function () {
//       page3Func(index + 1)
//     }
//   })
// }

// 第五页运动函数
function page5Func () {
  page5Swiper = new Swiper('#page5Swiper', {
    autoplay: {
      delay: 800,
      disableOnInteraction: false,
      stopOnLastSlide: true
    },
    preventInteractionOnTransition: true,
    speed: 400,
    observer: true,
    followFinger: false,
    lazy: {
      loadPrevNext: true,
      loadPrevNextAmount: 6
    },
    resistanceRatio: 0,
    on: {
      transitionEnd: function () {
        jedgePage5Arrow()
      }
    }
  })

  page5Swiper.autoplay.stop()

  $('.page5-left').on('touchstart', function () {
    page5Swiper.slidePrev()
  })
  $('.page5-right').on('touchstart', function () {
    page5Swiper.slideNext()
  })
}

// 判断的第五页箭头
function jedgePage5Arrow () {
  if (page5Swiper.activeIndex === 0) {
    $('.page5-left').css({
      display: 'none'
    })
  } else {
    $('.page5-left').css({
      display: 'block'
    })
  }

  if (page5Swiper.activeIndex === $('#page5Swiper .swiper-slide').length - 1) {
    $('.page5-right').css({
      display: 'none'
    })
  } else {
    $('.page5-right').css({
      display: 'block'
    })
  }
}

// 第9页SKU
// function page9Func () {
//   page9Swiper = new Swiper('#page9Swiper', {
//     autoplay: {
//       delay: 2000,
//       disableOnInteraction: false,
//       stopOnLastSlide: true
//     },
//     preventInteractionOnTransition: true,
//     speed: 600,
//     observer: true,
//     followFinger: false,
//     pagination: {
//       el: '#page9Swiper .swiper-pagination'
//     },
//     lazy: {
//       loadPrevNext: true,
//       loadPrevNextAmount: 5
//     },
//     resistanceRatio: 0,
//     on: {
//       transitionEnd: function () {
//         jedgePage9Arrow()
//       }
//     }
//   })
//   page9Swiper.autoplay.stop()
// }

function initPageHMove () {
  maxHPageCount = $('.swiper-slide-h').length
  console.log('maxHPageCount：' + maxHPageCount)
  $('.page9 .swiperH-button-prev').hide()
  $('.swiper-container-h').css({
    width: windowWidth,
    height: windowHeight
  })

  $('.swiper-container-h')
    .off('touchstart')
    .on('touchstart', function (e) {
      e.preventDefault()
      var startX = e.targetTouches[0].pageX
      var startY = e.targetTouches[0].pageY
      clearInterval(swiperTimer)
      $('.swiper-wrapper-h')
        .off('touchend')
        .on('touchend', function (endEv) {
          var endX = endEv.changedTouches[0].pageX
          var endY = endEv.changedTouches[0].pageY
          var direction = getDirection(startX, startY, endX, endY)
          if (direction === 'left' || direction === 'right') {
            hPageMove(direction)
          } else {
          }
        })
    })
}
function getAngle (angx, angy) {
  return (Math.atan2(angy, angx) * 180) / Math.PI
}

function getDirection (startx, starty, endx, endy) {
  var angx = endx - startx
  var angy = endy - starty
  var result = 'unmove'

  //如果滑动距离太短
  if (Math.abs(angx) < 2 && Math.abs(angy) < 2) {
    return result
  }

  var angle = getAngle(angx, angy)
  if (angle >= -135 && angle <= -45) {
    result = 'up'
  } else if (angle > 45 && angle < 135) {
    result = 'down'
  } else if (
    (angle >= 135 && angle <= 180) ||
    (angle >= -180 && angle < -135)
  ) {
    result = 'left'
  } else if (angle >= -45 && angle <= 45) {
    result = 'right'
  }

  return result
}

function hPageMove (direction) {
  if (!canHMove) return
  canHMove = false
  var index = direction === 'left' ? hPageActiveIndex + 1 : hPageActiveIndex - 1
  if (index < 0 || index > maxHPageCount - 1) {
    canHMove = true
    return
  }

  anime({
    targets: '#page9Swiper .swiper-wrapper-h',
    translateX: -windowWidth * index,
    easing: 'easeInOutQuad',
    duration: 400,
    complete: function () {
      hPageActiveIndex = index
      canHMove = true
      if (hPageActiveIndex === 0) {
        $('.page9 .swiperH-button-prev').hide()
      } else if (hPageActiveIndex === maxHPageCount - 1) {
        $('.page9 .swiperH-button-next').hide()
      } else {
        if ($('.page9 .swiperH-button-prev').is(':hidden')) {
          $('.page9 .swiperH-button-prev').show()
        }
        if ($('.page9 .swiperH-button-next').is(':hidden')) {
          $('.page9 .swiperH-button-next').show()
        }
      }
    }
  })
}
function hPageMoveFirst () {
  if (!canHMove) return
  canHMove = false
  anime({
    targets: '#page9Swiper .swiper-wrapper-h',
    translateX: 0,
    easing: 'easeInOutQuad',
    duration: 1,
    complete: function () {
      hPageActiveIndex = 0
      canHMove = true
      $('.page9 .swiperH-button-prev').hide()
    }
  })
}

function swiperTimerFunc () {
  // 一开始第一帧先只停留1.2秒，告知用户会轮播
  // 之后变回1.7秒
  setTimeout(function () {
    hPageMove('left')

    swiperTimer = setInterval(function () {
      hPageMove('left')
    }, 1000)
  }, 1200)
}

// 视频播放
function palayLiveBroadcast () {
  var video = $('#live-broadcast')[0]
  $('#page6Swiper').on('touchstart', function () {
    setTimeout(() => {
      $('#liveImg').addClass('display-n')
    }, 500)

    if (video.paused) {
      video.play()
      $('#video-btn').addClass('display-n')
    } else {
      video.pause()
      $('#video-btn').removeClass('display-n')
    }
  })
}
